<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>班级综合量化积分管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        success: '#52C41A',
                        danger: '#FF4D4F',
                        warning: '#FAAD14',
                        info: '#1890FF',
                        dark: '#1F2937',
                        light: '#F9FAFB'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    animation: {
                        'float': 'float 3s ease-in-out infinite',
                        'pulse-slow': 'pulse 4s cubic-bezier(0.4, 0, 0.6, 1) infinite',
                    },
                    keyframes: {
                        float: {
                            '0%, 100%': { transform: 'translateY(0)' },
                            '50%': { transform: 'translateY(-10px)' },
                        }
                    }
                },
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 10px 25px -5px rgba(22, 93, 255, 0.1), 0 8px 10px -6px rgba(22, 93, 255, 0.05);
            }
            .card-hover {
                transition: all 0.3s ease;
            }
            .card-hover:hover {
                transform: translateY(-5px);
                box-shadow: 0 20px 25px -5px rgba(22, 93, 255, 0.15), 0 10px 10px -5px rgba(22, 93, 255, 0.1);
            }
            .podium-1 {
                height: 180px;
                background-color: #FFD700;
            }
            .podium-2 {
                height: 140px;
                background-color: #C0C0C0;
            }
            .podium-3 {
                height: 100px;
                background-color: #CD7F32;
            }
            .highlight {
                animation: highlight 2s ease-in-out;
            }
            @keyframes highlight {
                0% { background-color: rgba(255, 255, 0, 0.5); }
                100% { background-color: transparent; }
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans text-dark min-h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-md sticky top-0 z-50 transition-all duration-300">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <!-- 左侧标题和图标 -->
            <div class="flex items-center space-x-3">
                <div class="w-10 h-10 rounded-lg bg-primary flex items-center justify-center text-white">
                    <i class="fa fa-trophy text-xl"></i>
                </div>
                <h1 class="text-xl md:text-2xl font-bold text-primary">班级综合量化积分管理系统</h1>
            </div>
            
            <!-- 右侧导航菜单 -->
            <nav class="hidden md:flex items-center space-x-6">
                <button id="nav-dashboard" class="nav-btn text-primary font-medium flex items-center">
                    <i class="fa fa-dashboard mr-2"></i>积分操作
                </button>
                <button id="nav-students" class="nav-btn text-gray-600 hover:text-primary font-medium flex items-center transition-colors">
                    <i class="fa fa-users mr-2"></i>学生管理
                </button>
                <button id="nav-ranking" class="nav-btn text-gray-600 hover:text-primary font-medium flex items-center transition-colors">
                    <i class="fa fa-bar-chart mr-2"></i>积分排行
                </button>
                <button id="nav-system" class="nav-btn text-gray-600 hover:text-primary font-medium flex items-center transition-colors">
                    <i class="fa fa-cog mr-2"></i>系统操作
                </button>
            </nav>
            
            <!-- 移动端菜单按钮 -->
            <button id="mobile-menu-btn" class="md:hidden text-gray-600 hover:text-primary">
                <i class="fa fa-bars text-xl"></i>
            </button>
        </div>
        
        <!-- 移动端导航菜单 -->
        <div id="mobile-menu" class="md:hidden hidden bg-white border-t">
            <div class="container mx-auto px-4 py-2 flex flex-col space-y-3">
                <button id="mobile-nav-dashboard" class="py-2 text-left text-primary font-medium flex items-center">
                    <i class="fa fa-dashboard mr-2"></i>积分操作
                </button>
                <button id="mobile-nav-students" class="py-2 text-left text-gray-600 hover:text-primary font-medium flex items-center transition-colors">
                    <i class="fa fa-users mr-2"></i>学生管理
                </button>
                <button id="mobile-nav-ranking" class="py-2 text-left text-gray-600 hover:text-primary font-medium flex items-center transition-colors">
                    <i class="fa fa-bar-chart mr-2"></i>积分排行
                </button>
                <button id="mobile-nav-system" class="py-2 text-left text-gray-600 hover:text-primary font-medium flex items-center transition-colors">
                    <i class="fa fa-cog mr-2"></i>系统操作
                </button>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="flex-grow container mx-auto px-4 py-6">
        <!-- 批量操作栏 - 默认隐藏 -->
        <div id="batch-operations" class="hidden mb-6 bg-white p-4 rounded-lg shadow-md flex flex-wrap items-center justify-between gap-4">
            <div class="flex items-center space-x-4">
                <label class="inline-flex items-center cursor-pointer">
                    <input type="checkbox" id="select-all" class="form-checkbox h-5 w-5 text-primary rounded border-gray-300">
                    <span class="ml-2 text-gray-700">全选</span>
                </label>
                <span id="selected-count" class="text-gray-600">已选择: 0 名学生</span>
            </div>
            <div class="flex space-x-3">
                <button id="batch-add" class="bg-success hover:bg-success/90 text-white px-4 py-2 rounded-lg flex items-center transition-colors">
                    <i class="fa fa-plus-circle mr-2"></i>批量加分
                </button>
                <button id="batch-subtract" class="bg-danger hover:bg-danger/90 text-white px-4 py-2 rounded-lg flex items-center transition-colors">
                    <i class="fa fa-minus-circle mr-2"></i>批量扣分
                </button>
            </div>
        </div>

        <!-- 1. 积分操作展示区 (默认显示) -->
        <section id="dashboard-section" class="space-y-6">
            <div class="text-center py-4">
                <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-gray-1200 mb-2">积分操作中心</h2>
                <p class="text-gray-600 max-w-2xl mx-auto">通过下方卡片对学生进行积分管理，支持单个操作和批量操作</p>
            </div>
            
            <!-- 新增：撤销和搜索工具栏 -->
            <div class="bg-white p-4 rounded-lg shadow-md flex flex-wrap items-center justify-between gap-4">
                <div class="flex items-center space-x-4">
                    <!-- 撤销按钮 -->
                    <button id="undo-btn" class="bg-warning hover:bg-warning/90 text-white px-4 py-2 rounded-lg flex items-center transition-colors disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                        <i class="fa fa-undo mr-2"></i>撤销上一步
                    </button>
                </div>
                <div class="flex-1 max-w-md">
                    <!-- 搜索框 -->
                    <div class="relative">
                        <input type="text" id="student-search" class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors" placeholder="搜索学生姓名...">
                        <i class="fa fa-search absolute left-3 top-3 text-gray-400"></i>
                    </div>
                </div>
            </div>
            
            <!-- 学生卡片容器 -->
            <div id="student-cards-container" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-3 gap-2">
                <!-- 初始提示卡片 -->
                <div class="col-span-full bg-white rounded-xl p-10 text-center card-shadow">
                    <div class="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fa fa-user-plus text-primary text-2xl"></i>
                    </div>
                    <h3 class="text-xl font-semibold text-gray-800 mb-2">暂无学生数据</h3>
                    <p class="text-gray-600 mb-6">请先到"学生管理"页面导入学生信息</p>
                    <button id="go-to-students" class="bg-primary hover:bg-primary/90 text-white px-6 py-3 rounded-lg font-medium transition-colors">
                        <i class="fa fa-users mr-2"></i>前往学生管理
                    </button>
                </div>
            </div>
        </section>

        <!-- 2. 学生管理界面 (默认隐藏) -->
        <section id="students-section" class="hidden space-y-6">
            <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div>
                    <h2 class="text-2xl font-bold text-gray-800">学生管理</h2>
                    <p class="text-gray-600">管理班级学生信息，支持导入和查看</p>
                </div>
                <button id="import-students-btn" class="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg flex items-center transition-colors self-start">
                    <i class="fa fa-upload mr-2"></i>导入学生
                </button>
            </div>
            
            <!-- 学生列表 -->
            <div class="bg-white rounded-xl shadow-md overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">序号</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">姓名</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">当前积分</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                            </tr>
                        </thead>
                        <tbody id="students-list" class="bg-white divide-y divide-gray-200">
                            <!-- 学生数据将通过JS动态填充 -->
                            <tr>
                                <td colspan="4" class="px-6 py-12 text-center text-gray-500">
                                    <div class="flex flex-col items-center">
                                        <i class="fa fa-info-circle text-3xl mb-3 text-gray-400"></i>
                                        <p>暂无学生数据，请点击"导入学生"按钮添加</p>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                
                <!-- 分页控制 (当有数据时显示) -->
                <div id="pagination" class="hidden px-6 py-4 bg-gray-50 border-t border-gray-200 flex items-center justify-between">
                    <div class="text-sm text-gray-700">
                        显示 <span id="showing-range">1-10</span> 条，共 <span id="total-students">0</span> 条
                    </div>
                    <div class="flex space-x-2">
                        <button id="prev-page" class="px-3 py-1 border border-gray-300 rounded-md bg-white text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                            <i class="fa fa-chevron-left"></i>
                        </button>
                        <button id="next-page" class="px-3 py-1 border border-gray-300 rounded-md bg-white text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                            <i class="fa fa-chevron-right"></i>
                        </button>
                    </div>
                </div>
            </div>
        </section>

        <!-- 3. 积分排行界面 (默认隐藏) -->
        <section id="ranking-section" class="hidden space-y-6">
            <div class="text-center">
                <h2 class="text-2xl font-bold text-gray-800">积分排行榜</h2>
                <p class="text-gray-600">班级学生积分排名情况</p>
            </div>
            
            <!-- 前三名领奖台 -->
            <div id="podium-container" class="mb-10">
                <div class="flex flex-col md:flex-row items-end justify-around gap-4 md:gap-8 py-6 px-4">
                    <!-- 第二名 -->
                    <div class="flex flex-col items-center w-full md:w-1/4">
                        <div class="podium-2 w-full rounded-t-lg flex items-end justify-center p-2">
                            <div class="text-center mb-2">
                                <div class="inline-block bg-warning text-white rounded-full w-8 h-8 flex items-center justify-center font-bold mb-1">2</div>
                                <p id="rank-2-name" class="font-medium">--</p>
                                <p id="rank-2-score" class="text-lg font-bold">0</p>
                            </div>
                        </div>
                        <div class="mt-2">
                            <i class="fa fa-medal text-xl text-gray-400"></i>
                        </div>
                    </div>
                    
                    <!-- 第一名 -->
                    <div class="flex flex-col items-center w-full md:w-1/4">
                        <div class="podium-1 w-full rounded-t-lg flex items-end justify-center p-2">
                            <div class="text-center mb-2">
                                <div class="inline-block bg-warning text-white rounded-full w-8 h-8 flex items-center justify-center font-bold mb-1">1</div>
                                <p id="rank-1-name" class="font-medium">--</p>
                                <p id="rank-1-score" class="text-lg font-bold">0</p>
                            </div>
                        </div>
                        <div class="mt-2">
                            <i class="fa fa-trophy text-2xl text-yellow-500"></i>
                        </div>
                    </div>
                    
                    <!-- 第三名 -->
                    <div class="flex flex-col items-center w-full md:w-1/4">
                        <div class="podium-3 w-full rounded-t-lg flex items-end justify-center p-2">
                            <div class="text-center mb-2">
                                <div class="inline-block bg-warning text-white rounded-full w-8 h-8 flex items-center justify-center font-bold mb-1">3</div>
                                <p id="rank-3-name" class="font-medium">--</p>
                                <p id="rank-3-score" class="text-lg font-bold">0</p>
                            </div>
                        </div>
                        <div class="mt-2">
                            <i class="fa fa-medal text-xl text-yellow-700"></i>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 完整排行榜 -->
            <div class="bg-white rounded-xl shadow-md overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">排名</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">姓名</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">积分</th>
                            </tr>
                        </thead>
                        <tbody id="ranking-list" class="bg-white divide-y divide-gray-200">
                            <!-- 排名数据将通过JS动态填充 -->
                            <tr>
                                <td colspan="3" class="px-6 py-12 text-center text-gray-500">
                                    <div class="flex flex-col items-center">
                                        <i class="fa fa-info-circle text-3xl mb-3 text-gray-400"></i>
                                        <p>暂无积分数据，请先添加学生并进行积分操作</p>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </section>

        <!-- 4. 系统操作界面 (默认隐藏) -->
        <section id="system-section" class="hidden space-y-6">
            <div>
                <h2 class="text-2xl font-bold text-gray-800">系统操作</h2>
                <p class="text-gray-600">系统设置、数据管理和规则配置</p>
            </div>
            
            <!-- 系统功能卡片 -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- 积分规则 -->
                <div class="bg-white rounded-xl shadow-md p-6 card-hover">
                    <div class="flex items-start justify-between mb-4">
                        <div class="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center text-primary">
                            <i class="fa fa-list-alt"></i>
                        </div>
                        <button id="score-rules-btn" class="text-primary hover:text-primary/80 font-medium transition-colors">
                            配置 <i class="fa fa-chevron-right ml-1 text-sm"></i>
                        </button>
                    </div>
                    <h3 class="text-lg font-semibold text-gray-800 mb-2">积分规则</h3>
                    <p class="text-gray-600">自定义积分规则，设置加分和扣分值及其对应含义</p>
                </div>
                
                <!-- 积分导出 -->
                <div class="bg-white rounded-xl shadow-md p-6 card-hover">
                    <div class="flex items-start justify-between mb-4">
                        <div class="w-10 h-10 rounded-lg bg-success/10 flex items-center justify-center text-success">
                            <i class="fa fa-download"></i>
                        </div>
                        <button id="export-scores-btn" class="text-success hover:text-success/80 font-medium transition-colors">
                            导出 <i class="fa fa-chevron-right ml-1 text-sm"></i>
                        </button>
                    </div>
                    <h3 class="text-lg font-semibold text-gray-800 mb-2">积分导出</h3>
                    <p class="text-gray-600">导出包含学生姓名和积分的TXT文档</p>
                </div>
                
                <!-- 数据备份 -->
                <div class="bg-white rounded-xl shadow-md p-6 card-hover">
                    <div class="flex items-start justify-between mb-4">
                        <div class="w-10 h-10 rounded-lg bg-info/10 flex items-center justify-center text-info">
                            <i class="fa fa-backup"></i>
                        </div>
                        <button id="backup-data-btn" class="text-info hover:text-info/80 font-medium transition-colors">
                            备份 <i class="fa fa-chevron-right ml-1 text-sm"></i>
                        </button>
                    </div>
                    <h3 class="text-lg font-semibold text-gray-800 mb-2">数据备份</h3>
                    <p class="text-gray-600">导出包含学生数据和操作日志的JSON备份文件</p>
                </div>
                
                <!-- 积分导入 -->
                <div class="bg-white rounded-xl shadow-md p-6 card-hover">
                    <div class="flex items-start justify-between mb-4">
                        <div class="w-10 h-10 rounded-lg bg-warning/10 flex items-center justify-center text-warning">
                            <i class="fa fa-upload"></i>
                        </div>
                        <label for="import-data-input" class="text-warning hover:text-warning/80 font-medium transition-colors cursor-pointer">
                            导入 <i class="fa fa-chevron-right ml-1 text-sm"></i>
                        </label>
                        <input type="file" id="import-data-input" accept=".json" class="hidden">
                    </div>
                    <h3 class="text-lg font-semibold text-gray-800 mb-2">积分导入</h3>
                    <p class="text-gray-600">导入备份的JSON文件，覆盖现有积分数据</p>
                </div>
                
                <!-- 操作日志 -->
                <div class="bg-white rounded-xl shadow-md p-6 card-hover">
                    <div class="flex items-start justify-between mb-4">
                        <div class="w-10 h-10 rounded-lg bg-secondary/10 flex items-center justify-center text-secondary">
                            <i class="fa fa-history"></i>
                        </div>
                        <button id="view-logs-btn" class="text-secondary hover:text-secondary/80 font-medium transition-colors">
                            查看 <i class="fa fa-chevron-right ml-1 text-sm"></i>
                        </button>
                    </div>
                    <h3 class="text-lg font-semibold text-gray-800 mb-2">操作日志</h3>
                    <p class="text-gray-600">查看系统操作记录，支持日志导出</p>
                </div>
                
                <!-- 积分清零 -->
                <div class="bg-white rounded-xl shadow-md p-6 card-hover">
                    <div class="flex items-start justify-between mb-4">
                        <div class="w-10 h-10 rounded-lg bg-danger/10 flex items-center justify-center text-danger">
                            <i class="fa fa-refresh"></i>
                        </div>
                        <button id="reset-scores-btn" class="text-danger hover:text-danger/80 font-medium transition-colors">
                            清零 <i class="fa fa-chevron-right ml-1 text-sm"></i>
                        </button>
                    </div>
                    <h3 class="text-lg font-semibold text-gray-800 mb-2">积分清零</h3>
                    <p class="text-gray-600">将所有学生的积分数值重置为零</p>
                </div>
                
                <!-- 系统初始化 -->
                <div class="bg-white rounded-xl shadow-md p-6 card-hover md:col-span-2 border-l-4 border-danger">
                    <div class="flex items-start justify-between mb-4">
                        <div class="w-10 h-10 rounded-lg bg-danger/10 flex items-center justify-center text-danger">
                            <i class="fa fa-eraser"></i>
                        </div>
                        <button id="system-reset-btn" class="text-danger hover:text-danger/80 font-medium transition-colors">
                            初始化 <i class="fa fa-chevron-right ml-1 text-sm"></i>
                        </button>
                    </div>
                    <h3 class="text-lg font-semibold text-gray-800 mb-2">系统初始化</h3>
                    <p class="text-gray-600 text-danger">清除全部数据，包括学生信息、积分和日志，恢复到初始状态 <span class="font-medium">此操作不可恢复！</span></p>
                </div>
            </div>
        </section>
    </main>

    <!-- 页脚 -->
    <footer class="bg-dark text-white py-6">
        <div class="container mx-auto px-4 text-center">
            <p>班级综合量化积分管理系统 &copy; 2025</p>
            <p class="text-gray-400 text-sm mt-1">支持离线使用 | 本地数据存储 | 设计：Lwaves</p>
        </div>
    </footer>

    <!-- 模态框 - 导入学生 -->
    <div id="import-students-modal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex items-center justify-center p-4">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
                <h3 class="text-xl font-bold text-gray-800">导入学生</h3>
                <button id="close-import-modal" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            <div class="px-6 py-4 flex-grow overflow-y-auto">
                <p class="text-gray-600 mb-4">请在下方文本框中输入学生姓名，每行一个学生</p>
                <textarea id="students-input" class="w-full h-64 p-4 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors resize-none" placeholder="张三&#10;李四&#10;王五&#10;..."></textarea>
                <div class="mt-4 text-sm text-gray-500">
                    <p><i class="fa fa-info-circle mr-1"></i> 已存在的学生不会被重复添加</p>
                </div>
            </div>
            <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
                <button id="cancel-import" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">取消</button>
                <button id="confirm-import" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">确认导入</button>
            </div>
        </div>
    </div>

    <!-- 模态框 - 积分规则设置 -->
    <div id="score-rules-modal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex items-center justify-center p-4">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
                <h3 class="text-xl font-bold text-gray-800">积分规则设置</h3>
                <button id="close-rules-modal" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            <div class="px-6 py-4 flex-grow overflow-y-auto">
                <!-- 加分规则 -->
                <div class="mb-6">
                    <h4 class="text-lg font-semibold text-gray-800 mb-3 flex items-center">
                        <i class="fa fa-plus-circle text-success mr-2"></i>加分规则
                    </h4>
                    <div id="add-rules-container" class="space-y-3">
                        <div class="flex items-center space-x-3 add-rule-item">
                            <input type="number" class="score-value w-20 p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" placeholder="分值" min="1" value="1">
                            <input type="text" class="score-desc flex-grow p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" placeholder="含义描述">
                            <button class="remove-rule-btn text-gray-400 hover:text-danger p-2">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    </div>
                    <button id="add-add-rule" class="mt-3 text-primary hover:text-primary/80 text-sm flex items-center">
                        <i class="fa fa-plus-circle mr-1"></i> 添加加分规则
                    </button>
                </div>
                
                <!-- 扣分规则 -->
                <div>
                    <h4 class="text-lg font-semibold text-gray-800 mb-3 flex items-center">
                        <i class="fa fa-minus-circle text-danger mr-2"></i>扣分规则
                    </h4>
                    <div id="subtract-rules-container" class="space-y-3">
                        <div class="flex items-center space-x-3 subtract-rule-item">
                            <input type="number" class="score-value w-20 p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" placeholder="分值" max="-1" value="-1">
                            <input type="text" class="score-desc flex-grow p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" placeholder="含义描述">
                            <button class="remove-rule-btn text-gray-400 hover:text-danger p-2">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    </div>
                    <button id="add-subtract-rule" class="mt-3 text-primary hover:text-primary/80 text-sm flex items-center">
                        <i class="fa fa-plus-circle mr-1"></i> 添加扣分规则
                    </button>
                </div>
            </div>
            <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
                <button id="cancel-rules" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">取消</button>
                <button id="save-rules" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">保存规则</button>
            </div>
        </div>
    </div>

    <!-- 模态框 - 批量操作 -->
    <div id="batch-operation-modal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex items-center justify-center p-4">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-md overflow-hidden flex flex-col">
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
                <h3 id="batch-modal-title" class="text-xl font-bold text-gray-800">批量加分</h3>
                <button id="close-batch-modal" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            <div class="px-6 py-6">
                <p class="text-gray-600 mb-4">请选择要批量操作的分值</p>
                <div id="batch-scores-container" class="grid grid-cols-3 gap-3">
                    <!-- 分值按钮将通过JS动态填充 -->
                </div>
                <div class="mt-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">操作原因 (可选)</label>
                    <input type="text" id="batch-reason" class="w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" placeholder="请输入操作原因">
                </div>
            </div>
            <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
                <button id="cancel-batch" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">取消</button>
                <button id="confirm-batch" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">确认操作</button>
            </div>
        </div>
    </div>

    <!-- 模态框 - 操作日志 -->
    <div id="logs-modal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex items-center justify-center p-4">
        <div class="bg-white rounded-xl shadow-xl w-full max-w-3xl max-h-[90vh] overflow-hidden flex flex-col">
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
                <h3 class="text-xl font-bold text-gray-800">操作日志</h3>
                <div class="flex items-center space-x-4">
                    <button id="export-logs-btn" class="text-primary hover:text-primary/80 flex items-center text-sm">
                        <i class="fa fa-download mr-1"></i> 导出日志
                    </button>
                    <button id="close-logs-modal" class="text-gray-500 hover:text-gray-700">
                        <i class="fa fa-times text-xl"></i>
                    </button>
                </div>
            </div>
            <div class="px-6 py-4 flex-grow overflow-y-auto">
                <div id="logs-container" class="space-y-3">
                    <!-- 日志内容将通过JS动态填充 -->
                    <div class="text-center text-gray-500 py-10">
                        <i class="fa fa-info-circle text-3xl mb-3 text-gray-400"></i>
                        <p>暂无操作日志</p>
                    </div>
                </div>
            </div>
            <div class="px-6 py-4 border-t border-gray-200 flex justify-end">
                <button id="close-logs" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">关闭</button>
            </div>
        </div>
    </div>

    <!-- 通知提示框 -->
    <div id="toast" class="fixed bottom-6 right-6 bg-dark text-white px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50">
        <i id="toast-icon" class="fa fa-check-circle mr-2"></i>
        <span id="toast-message">操作成功</span>
    </div>

    <script>
        // 全局变量
        let currentSection = 'dashboard';
        let selectedStudents = new Set();
        let currentBatchOperation = 'add'; // 'add' 或 'subtract'
        let db;
        let currentPage = 1;
        const studentsPerPage = 10;
        
        // 新增：操作历史记录
        let operationHistory = [];

        // DOM 加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化数据库
            initDB();
            
            // 导航菜单切换
            setupNavigation();
            
            // 初始化模态框事件
            setupModals();
            
            // 初始化系统操作事件
            setupSystemOperations();
            
            // 初始化批量操作
            setupBatchOperations();
            
            // 初始化积分规则
            setupScoreRules();
            
            // 移动端菜单切换
            document.getElementById('mobile-menu-btn').addEventListener('click', function() {
                const mobileMenu = document.getElementById('mobile-menu');
                mobileMenu.classList.toggle('hidden');
            });
            
            // 前往学生管理按钮
            document.getElementById('go-to-students').addEventListener('click', function() {
                switchSection('students');
                // 关闭移动端菜单（如果打开）
                document.getElementById('mobile-menu').classList.add('hidden');
            });
            
            // 新增：撤销按钮事件
            document.getElementById('undo-btn').addEventListener('click', undoLastOperation);
            
            // 新增：搜索框事件
            document.getElementById('student-search').addEventListener('input', function() {
                filterStudentsByName(this.value);
            });
        });

        // 初始化数据库
        function initDB() {
            const request = indexedDB.open('ClassScoreDB', 2); // 版本号增加到2
            
            request.onupgradeneeded = function(event) {
                db = event.target.result;
                
                // 创建学生表
                if (!db.objectStoreNames.contains('students')) {
                    const studentsStore = db.createObjectStore('students', { keyPath: 'id', autoIncrement: true });
                    studentsStore.createIndex('name', 'name', { unique: true });
                }
                
                // 创建积分规则表
                if (!db.objectStoreNames.contains('scoreRules')) {
                    const rulesStore = db.createObjectStore('scoreRules', { keyPath: 'type' });
                }
                
                // 创建操作日志表
                if (!db.objectStoreNames.contains('logs')) {
                    const logsStore = db.createObjectStore('logs', { keyPath: 'id', autoIncrement: true });
                    logsStore.createIndex('timestamp', 'timestamp', { unique: false });
                }
                
                // 新增：创建操作历史表
                if (!db.objectStoreNames.contains('operationHistory')) {
                    const historyStore = db.createObjectStore('operationHistory', { keyPath: 'id', autoIncrement: true });
                    historyStore.createIndex('timestamp', 'timestamp', { unique: false });
                }
                
                // 初始化默认积分规则
                const defaultRules = [
                    {
                        type: 'add',
                        rules: [
                            { value: 1, desc: '其他加分' },
                            { value: 2, desc: '主动提问' },
                            { value: 3, desc: '勇担重任' },
                            { value: 4, desc: '老师表扬' },
                            { value: 5, desc: '主动服务' }
                        ]
                    },
                    {
                        type: 'subtract',
                        rules: [
                            { value: -1, desc: '其他扣分' },
                            { value: -2, desc: '上课迟到' },
                            { value: -3, desc: '缺交作业' },
                            { value: -4, desc: '课堂违纪' },
                            { value: -5, desc: '教师投诉' }
                        ]
                    }
                ];
                
                const transaction = event.target.transaction;
                const rulesStore = transaction.objectStore('scoreRules');
                
                defaultRules.forEach(rule => {
                    rulesStore.add(rule);
                });
            };
            
            request.onsuccess = function(event) {
                db = event.target.result;
                // 加载数据
                loadStudents();
                loadScoreRules();
                updateDashboard();
                updateRanking();
                // 新增：加载操作历史
                loadOperationHistory();
            };
            
            request.onerror = function(event) {
                showToast('数据库初始化失败: ' + event.target.error, 'error');
            };
        }

        // 设置导航切换
        function setupNavigation() {
            // 桌面端导航
            document.getElementById('nav-dashboard').addEventListener('click', function() {
                switchSection('dashboard');
                document.getElementById('mobile-menu').classList.add('hidden');
            });
            document.getElementById('nav-students').addEventListener('click', function() {
                switchSection('students');
                document.getElementById('mobile-menu').classList.add('hidden');
            });
            document.getElementById('nav-ranking').addEventListener('click', function() {
                switchSection('ranking');
                document.getElementById('mobile-menu').classList.add('hidden');
            });
            document.getElementById('nav-system').addEventListener('click', function() {
                switchSection('system');
                document.getElementById('mobile-menu').classList.add('hidden');
            });
            
            // 移动端导航
            document.getElementById('mobile-nav-dashboard').addEventListener('click', function() {
                switchSection('dashboard');
                document.getElementById('mobile-menu').classList.add('hidden');
            });
            document.getElementById('mobile-nav-students').addEventListener('click', function() {
                switchSection('students');
                document.getElementById('mobile-menu').classList.add('hidden');
            });
            document.getElementById('mobile-nav-ranking').addEventListener('click', function() {
                switchSection('ranking');
                document.getElementById('mobile-menu').classList.add('hidden');
            });
            document.getElementById('mobile-nav-system').addEventListener('click', function() {
                switchSection('system');
                document.getElementById('mobile-menu').classList.add('hidden');
            });
        }

        // 切换显示的 section
        function switchSection(section) {
            // 隐藏所有 section
            document.getElementById('dashboard-section').classList.add('hidden');
            document.getElementById('students-section').classList.add('hidden');
            document.getElementById('ranking-section').classList.add('hidden');
            document.getElementById('system-section').classList.add('hidden');
            
            // 重置导航按钮样式
            document.querySelectorAll('.nav-btn').forEach(btn => {
                btn.classList.remove('text-primary');
                btn.classList.add('text-gray-600', 'hover:text-primary');
            });
            
            // 显示选中的 section
            document.getElementById(`${section}-section`).classList.remove('hidden');
            
            // 更新导航按钮样式
            document.getElementById(`nav-${section}`).classList.remove('text-gray-600', 'hover:text-primary');
            document.getElementById(`nav-${section}`).classList.add('text-primary');
            document.getElementById(`mobile-nav-${section}`).classList.remove('text-gray-600', 'hover:text-primary');
            document.getElementById(`mobile-nav-${section}`).classList.add('text-primary');
            
            // 更新当前 section
            currentSection = section;
            
            // 特定 section 的额外处理
            if (section === 'students') {
                loadStudents();
            } else if (section === 'ranking') {
                updateRanking();
            } else if (section === 'dashboard') {
                updateDashboard();
            }
        }

        // 设置模态框事件
        function setupModals() {
            // 导入学生模态框
            document.getElementById('import-students-btn').addEventListener('click', function() {
                document.getElementById('import-students-modal').classList.remove('hidden');
                document.getElementById('students-input').focus();
            });
            
            document.getElementById('close-import-modal').addEventListener('click', function() {
                document.getElementById('import-students-modal').classList.add('hidden');
            });
            
            document.getElementById('cancel-import').addEventListener('click', function() {
                document.getElementById('import-students-modal').classList.add('hidden');
            });
            
            document.getElementById('confirm-import').addEventListener('click', importStudents);
            
            // 积分规则模态框
            document.getElementById('score-rules-btn').addEventListener('click', function() {
                document.getElementById('score-rules-modal').classList.remove('hidden');
                loadScoreRulesIntoForm();
            });
            
            document.getElementById('close-rules-modal').addEventListener('click', function() {
                document.getElementById('score-rules-modal').classList.add('hidden');
            });
            
            document.getElementById('cancel-rules').addEventListener('click', function() {
                document.getElementById('score-rules-modal').classList.add('hidden');
            });
            
            document.getElementById('save-rules').addEventListener('click', saveScoreRules);
            
            // 添加加分规则按钮
            document.getElementById('add-add-rule').addEventListener('click', function() {
                addRuleItem('add');
            });
            
            // 添加扣分规则按钮
            document.getElementById('add-subtract-rule').addEventListener('click', function() {
                addRuleItem('subtract');
            });
            
            // 日志模态框
            document.getElementById('view-logs-btn').addEventListener('click', function() {
                document.getElementById('logs-modal').classList.remove('hidden');
                loadLogs();
            });
            
            document.getElementById('close-logs-modal').addEventListener('click', function() {
                document.getElementById('logs-modal').classList.add('hidden');
            });
            
            document.getElementById('close-logs').addEventListener('click', function() {
                document.getElementById('logs-modal').classList.add('hidden');
            });
        }

        // 设置系统操作事件
        function setupSystemOperations() {
            // 导出积分
            document.getElementById('export-scores-btn').addEventListener('click', exportScores);
            
            // 备份数据
            document.getElementById('backup-data-btn').addEventListener('click', backupData);
            
            // 导入数据
            document.getElementById('import-data-input').addEventListener('change', importData);
            
            // 导出日志
            document.getElementById('export-logs-btn').addEventListener('click', exportLogs);
            
            // 积分清零
            document.getElementById('reset-scores-btn').addEventListener('click', function() {
                if (confirm('确定要将所有学生的积分清零吗？此操作不可撤销！')) {
                    resetAllScores();
                }
            });
            
            // 系统初始化
            document.getElementById('system-reset-btn').addEventListener('click', function() {
                if (confirm('确定要初始化系统吗？这将清除所有数据，包括学生信息、积分和日志，且不可恢复！')) {
                    resetSystem();
                }
            });
        }

        // 设置批量操作
        function setupBatchOperations() {
            // 全选/取消全选
            document.getElementById('select-all').addEventListener('change', function(e) {
                const isChecked = e.target.checked;
                const checkboxes = document.querySelectorAll('.student-checkbox');
                
                checkboxes.forEach(checkbox => {
                    checkbox.checked = isChecked;
                    const studentId = parseInt(checkbox.dataset.id);
                    
                    if (isChecked) {
                        selectedStudents.add(studentId);
                    } else {
                        selectedStudents.delete(studentId);
                    }
                });
                
                updateBatchOperations();
            });
            
            // 批量加分
            document.getElementById('batch-add').addEventListener('click', function() {
                currentBatchOperation = 'add';
                document.getElementById('batch-modal-title').textContent = '批量加分';
                document.getElementById('batch-operation-modal').classList.remove('hidden');
                loadBatchScores('add');
            });
            
            // 批量扣分
            document.getElementById('batch-subtract').addEventListener('click', function() {
                currentBatchOperation = 'subtract';
                document.getElementById('batch-modal-title').textContent = '批量扣分';
                document.getElementById('batch-operation-modal').classList.remove('hidden');
                loadBatchScores('subtract');
            });
            
            // 关闭批量操作模态框
            document.getElementById('close-batch-modal').addEventListener('click', function() {
                document.getElementById('batch-operation-modal').classList.add('hidden');
            });
            
            document.getElementById('cancel-batch').addEventListener('click', function() {
                document.getElementById('batch-operation-modal').classList.add('hidden');
            });
            
            // 确认批量操作
            document.getElementById('confirm-batch').addEventListener('click', confirmBatchOperation);
        }

        // 设置积分规则
        function setupScoreRules() {
            // 为规则项的删除按钮添加事件委托
            document.getElementById('add-rules-container').addEventListener('click', function(e) {
                if (e.target.closest('.remove-rule-btn')) {
                    const item = e.target.closest('.add-rule-item');
                    if (document.querySelectorAll('.add-rule-item').length > 1) {
                        item.remove();
                    } else {
                        showToast('至少保留一条规则', 'warning');
                    }
                }
            });
            
            document.getElementById('subtract-rules-container').addEventListener('click', function(e) {
                if (e.target.closest('.remove-rule-btn')) {
                    const item = e.target.closest('.subtract-rule-item');
                    if (document.querySelectorAll('.subtract-rule-item').length > 1) {
                        item.remove();
                    } else {
                        showToast('至少保留一条规则', 'warning');
                    }
                }
            });
        }

        // 导入学生
        function importStudents() {
            const text = document.getElementById('students-input').value.trim();
            if (!text) {
                showToast('请输入学生姓名', 'warning');
                return;
            }
            
            const names = text.split('\n')
                .map(name => name.trim())
                .filter(name => name);
            
            if (names.length === 0) {
                showToast('请输入有效的学生姓名', 'warning');
                return;
            }
            
            const transaction = db.transaction('students', 'readwrite');
            const store = transaction.objectStore('students');
            const nameIndex = store.index('name');
            
            let addedCount = 0;
            let existsCount = 0;
            
            names.forEach(name => {
                const request = nameIndex.get(name);
                
                request.onsuccess = function() {
                    if (!request.result) {
                        // 学生不存在，添加
                        store.add({
                            name: name,
                            score: 0,
                            createdAt: new Date().toISOString()
                        });
                        addedCount++;
                    } else {
                        // 学生已存在
                        existsCount++;
                    }
                };
            });
            
            transaction.oncomplete = function() {
                showToast(`成功导入 ${addedCount} 名学生，${existsCount} 名学生已存在`, 'success');
                document.getElementById('import-students-modal').classList.add('hidden');
                document.getElementById('students-input').value = '';
                
                // 更新学生列表和仪表盘
                loadStudents();
                updateDashboard();
                updateRanking();
                
                // 记录日志
                addLog(`导入学生: 成功导入 ${addedCount} 名，${existsCount} 名已存在`);
            };
            
            transaction.onerror = function() {
                showToast('导入失败: ' + transaction.error, 'error');
            };
        }

        // 加载学生列表
        function loadStudents() {
            const transaction = db.transaction('students', 'readonly');
            const store = transaction.objectStore('students');
            const request = store.getAll();
            
            request.onsuccess = function() {
                const students = request.result;
                const studentsList = document.getElementById('students-list');
                const pagination = document.getElementById('pagination');
                const totalStudentsEl = document.getElementById('total-students');
                const showingRangeEl = document.getElementById('showing-range');
                const prevPageBtn = document.getElementById('prev-page');
                const nextPageBtn = document.getElementById('next-page');
                
                totalStudentsEl.textContent = students.length;
                
                if (students.length === 0) {
                    studentsList.innerHTML = `
                        <tr>
                            <td colspan="4" class="px-6 py-12 text-center text-gray-500">
                                <div class="flex flex-col items-center">
                                    <i class="fa fa-info-circle text-3xl mb-3 text-gray-400"></i>
                                    <p>暂无学生数据，请点击"导入学生"按钮添加</p>
                                </div>
                            </td>
                        </tr>
                    `;
                    pagination.classList.add('hidden');
                    return;
                }
                
                // 分页处理
                const totalPages = Math.ceil(students.length / studentsPerPage);
                const startIndex = (currentPage - 1) * studentsPerPage;
                const endIndex = Math.min(startIndex + studentsPerPage, students.length);
                const paginatedStudents = students.slice(startIndex, endIndex);
                
                // 更新显示范围
                showingRangeEl.textContent = `${startIndex + 1}-${endIndex}`;
                
                // 更新分页按钮状态
                prevPageBtn.disabled = currentPage === 1;
                nextPageBtn.disabled = currentPage === totalPages;
                
                // 渲染学生列表
                studentsList.innerHTML = '';
                paginatedStudents.forEach((student, index) => {
                    const tr = document.createElement('tr');
                    tr.className = 'hover:bg-gray-50 transition-colors';
                    tr.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${startIndex + index + 1}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${student.name}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 ${student.score > 0 ? 'text-success' : student.score < 0 ? 'text-danger' : ''}">${student.score}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            <button class="edit-student text-primary hover:text-primary/80 mr-3" data-id="${student.id}">编辑</button>
                            <button class="delete-student text-danger hover:text-danger/80" data-id="${student.id}">删除</button>
                        </td>
                    `;
                    studentsList.appendChild(tr);
                });
                
                // 添加编辑和删除事件
                document.querySelectorAll('.edit-student').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const studentId = parseInt(this.dataset.id);
                        editStudent(studentId);
                    });
                });
                
                document.querySelectorAll('.delete-student').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const studentId = parseInt(this.dataset.id);
                        if (confirm('确定要删除该学生吗？')) {
                            deleteStudent(studentId);
                        }
                    });
                });
                
                // 分页按钮事件
                prevPageBtn.onclick = function() {
                    if (currentPage > 1) {
                        currentPage--;
                        loadStudents();
                    }
                };
                
                nextPageBtn.onclick = function() {
                    if (currentPage < totalPages) {
                        currentPage++;
                        loadStudents();
                    }
                };
                
                pagination.classList.remove('hidden');
            };
            
            request.onerror = function() {
                showToast('加载学生失败: ' + request.error, 'error');
            };
        }

        // 编辑学生
        function editStudent(studentId) {
            const transaction = db.transaction('students', 'readonly');
            const store = transaction.objectStore('students');
            const request = store.get(studentId);
            
            request.onsuccess = function() {
                const student = request.result;
                if (!student) {
                    showToast('学生不存在', 'error');
                    return;
                }
                
                const newName = prompt('请输入学生姓名', student.name);
                if (newName === null) return; // 取消操作
                
                const trimmedName = newName.trim();
                if (!trimmedName) {
                    showToast('学生姓名不能为空', 'warning');
                    return;
                }
                
                // 检查姓名是否已存在
                const nameIndex = store.index('name');
                const nameRequest = nameIndex.get(trimmedName);
                
                nameRequest.onsuccess = function() {
                    if (nameRequest.result && nameRequest.result.id !== studentId) {
                        showToast('该学生姓名已存在', 'error');
                        return;
                    }
                    
                    // 更新学生信息
                    const updateTransaction = db.transaction('students', 'readwrite');
                    const updateStore = updateTransaction.objectStore('students');
                    
                    student.name = trimmedName;
                    const updateRequest = updateStore.put(student);
                    
                    updateRequest.onsuccess = function() {
                        showToast('学生信息更新成功', 'success');
                        loadStudents();
                        updateDashboard();
                        updateRanking();
                        
                        // 记录日志
                        addLog(`更新学生信息: ${student.name}`);
                    };
                    
                    updateRequest.onerror = function() {
                        showToast('更新学生信息失败: ' + updateRequest.error, 'error');
                    };
                };
            };
            
            request.onerror = function() {
                showToast('获取学生信息失败: ' + request.error, 'error');
            };
        }

        // 删除学生
        function deleteStudent(studentId) {
            const transaction = db.transaction('students', 'readwrite');
            const store = transaction.objectStore('students');
            const request = store.get(studentId);
            
            request.onsuccess = function() {
                const student = request.result;
                if (!student) {
                    showToast('学生不存在', 'error');
                    return;
                }
                
                const deleteRequest = store.delete(studentId);
                
                deleteRequest.onsuccess = function() {
                    showToast(`已删除学生: ${student.name}`, 'success');
                    loadStudents();
                    updateDashboard();
                    updateRanking();
                    
                    // 记录日志
                    addLog(`删除学生: ${student.name}`);
                };
                
                deleteRequest.onerror = function() {
                    showToast('删除学生失败: ' + deleteRequest.error, 'error');
                };
            };
        }

        // 更新积分操作展示区
        function updateDashboard() {
            const transaction = db.transaction(['students', 'scoreRules'], 'readonly');
            const studentsStore = transaction.objectStore('students');
            const rulesStore = transaction.objectStore('scoreRules');
            
            let students;
            let addRules = [];
            let subtractRules = [];
            
            // 获取学生
            const studentsRequest = studentsStore.getAll();
            studentsRequest.onsuccess = function() {
                students = studentsRequest.result;
            };
            
            // 获取加分规则
            const addRulesRequest = rulesStore.get('add');
            addRulesRequest.onsuccess = function() {
                addRules = addRulesRequest.result?.rules || [];
            };
            
            // 获取扣分规则
            const subtractRulesRequest = rulesStore.get('subtract');
            subtractRulesRequest.onsuccess = function() {
                subtractRules = subtractRulesRequest.result?.rules || [];
            };
            
            transaction.oncomplete = function() {
                const container = document.getElementById('student-cards-container');
                
                if (students.length === 0) {
                    container.innerHTML = `
                        <div class="col-span-full bg-white rounded-xl p-8 text-center card-shadow">
                            <div class="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fa fa-user-plus text-primary text-2xl"></i>
                            </div>
                            <h3 class="text-xl font-semibold text-gray-800 mb-2">暂无学生数据</h3>
                            <p class="text-gray-600 mb-6">请先到"学生管理"页面导入学生信息</p>
                            <button id="go-to-students" class="bg-primary hover:bg-primary/90 text-white px-6 py-3 rounded-lg font-medium transition-colors">
                                <i class="fa fa-users mr-2"></i>前往学生管理
                            </button>
                        </div>
                    `;
                    
                    // 重新绑定按钮事件
                    document.getElementById('go-to-students').addEventListener('click', function() {
                        switchSection('students');
                    });
                    
                    // 隐藏批量操作栏
                    document.getElementById('batch-operations').classList.add('hidden');
                    selectedStudents.clear();
                    
                    return;
                }
                
                // 显示批量操作栏
                document.getElementById('batch-operations').classList.remove('hidden');
                
                // 清空容器
                container.innerHTML = '';
                
                // 添加学生卡片
                students.forEach((student, index) => {
                    const card = document.createElement('div');
                    card.className = 'bg-white rounded-xl p-6 card-shadow card-hover animate-float';
                    card.style.animationDelay = `${index * 0.1}s`;
                    card.dataset.studentName = student.name; // 为搜索功能添加数据属性
                    
                    // 构建加分按钮HTML
                    const addButtonsHtml = addRules.map(rule => `
                        <button class="add-score-btn bg-success/10 hover:bg-success/20 text-success px-3 py-1 rounded-md text-sm transition-colors m-1" 
                                data-id="${student.id}" data-value="${rule.value}" 
                                title="${rule.desc || `+${rule.value}分`}">
                            +${rule.value}
                        </button>
                    `).join('');
                    
                    // 构建扣分按钮HTML
                    const subtractButtonsHtml = subtractRules.map(rule => `
                        <button class="subtract-score-btn bg-danger/10 hover:bg-danger/20 text-danger px-3 py-1 rounded-md text-sm transition-colors m-1" 
                                data-id="${student.id}" data-value="${rule.value}"
                                title="${rule.desc || `${rule.value}分`}">
                            ${rule.value}
                        </button>
                    `).join('');
                    
                    card.innerHTML = `
                        <div class="flex items-start justify-between mb-4">
                            <label class="inline-flex items-center cursor-pointer">
                                <input type="checkbox" class="student-checkbox form-checkbox h-4 w-4 text-primary rounded border-gray-300" data-id="${student.id}">
                            </label>
                            <span class="text-gray-500 text-sm">ID: ${student.id}</span>
                        </div>
                        <h3 class="text-xl font-bold text-center text-gray-800 mb-2">${student.name}</h3>
                        <div class="text-center mb-4">
                            <span class="text-4xl font-bold ${student.score > 0 ? 'text-success' : student.score < 0 ? 'text-danger' : 'text-gray-700'}">${student.score}</span>
                            <span class="text-gray-500 ml-1">分</span>
                        </div>
                        <div class="flex flex-wrap justify-center gap-1 mb-3">
                            ${addButtonsHtml}
                        </div>
                        <div class="flex flex-wrap justify-center gap-1">
                            ${subtractButtonsHtml}
                        </div>
                    `;
                    
                    container.appendChild(card);
                });
                
                // 为学生复选框添加事件
                document.querySelectorAll('.student-checkbox').forEach(checkbox => {
                    checkbox.addEventListener('change', function(e) {
                        const studentId = parseInt(this.dataset.id);
                        
                        if (e.target.checked) {
                            selectedStudents.add(studentId);
                        } else {
                            selectedStudents.delete(studentId);
                            // 取消全选
                            document.getElementById('select-all').checked = false;
                        }
                        
                        updateBatchOperations();
                    });
                });
                
                // 为加分按钮添加事件
                document.querySelectorAll('.add-score-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const studentId = parseInt(this.dataset.id);
                        const value = parseInt(this.dataset.value);
                        const desc = this.title;
                        updateStudentScore(studentId, value, desc);
                    });
                });
                
                // 为扣分按钮添加事件
                document.querySelectorAll('.subtract-score-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const studentId = parseInt(this.dataset.id);
                        const value = parseInt(this.dataset.value);
                        const desc = this.title;
                        updateStudentScore(studentId, value, desc);
                    });
                });
                
                // 更新批量操作状态
                updateBatchOperations();
            };
        }

        // 更新批量操作状态
        function updateBatchOperations() {
            const count = selectedStudents.size;
            document.getElementById('selected-count').textContent = `已选择: ${count} 名学生`;
            
            // 禁用或启用批量操作按钮
            const batchButtons = [
                document.getElementById('batch-add'),
                document.getElementById('batch-subtract')
            ];
            
            batchButtons.forEach(btn => {
                if (count === 0) {
                    btn.disabled = true;
                    btn.classList.add('opacity-50', 'cursor-not-allowed');
                } else {
                    btn.disabled = false;
                    btn.classList.remove('opacity-50', 'cursor-not-allowed');
                }
            });
        }

        // 更新学生积分
        function updateStudentScore(studentId, value, reason = '') {
            const transaction = db.transaction('students', 'readwrite');
            const store = transaction.objectStore('students');
            const request = store.get(studentId);
            
            request.onsuccess = function() {
                const student = request.result;
                if (!student) {
                    showToast('学生不存在', 'error');
                    return;
                }
                
                const oldScore = student.score;
                student.score = oldScore + value;
                
                const updateRequest = store.put(student);
                
                updateRequest.onsuccess = function() {
                    const action = value > 0 ? '加分' : '扣分';
                    const message = `${student.name} ${action} ${Math.abs(value)}分，当前积分: ${student.score}`;
                    showToast(message, 'success');
                    
                    // 新增：记录操作历史
                    addOperationHistory({
                        studentId: studentId,
                        studentName: student.name,
                        oldScore: oldScore,
                        newScore: student.score,
                        value: value,
                        reason: reason,
                        timestamp: new Date().toISOString()
                    });
                    
                    // 更新界面
                    updateDashboard();
                    updateRanking();
                    
                    // 记录日志
                    const logReason = reason ? `，原因: ${reason}` : '';
                    addLog(`${student.name} ${action} ${Math.abs(value)}分${logReason}，从 ${oldScore} 变为 ${student.score}`);
                };
                
                updateRequest.onerror = function() {
                    showToast('更新积分失败: ' + updateRequest.error, 'error');
                };
            };
        }

        // 加载积分规则
        function loadScoreRules() {
            const transaction = db.transaction('scoreRules', 'readonly');
            const store = transaction.objectStore('scoreRules');
            
            // 后续可以在这里使用积分规则数据
        }

        // 加载积分规则到表单
        function loadScoreRulesIntoForm() {
            const transaction = db.transaction('scoreRules', 'readonly');
            const store = transaction.objectStore('scoreRules');
            
            // 清空现有规则项
            document.getElementById('add-rules-container').innerHTML = '';
            document.getElementById('subtract-rules-container').innerHTML = '';
            
            // 获取加分规则
            const addRulesRequest = store.get('add');
            addRulesRequest.onsuccess = function() {
                const addRules = addRulesRequest.result?.rules || [
                    { value: 1, desc: '' },
                    { value: 2, desc: '' }
                ];
                
                addRules.forEach(rule => {
                    addRuleItem('add', rule.value, rule.desc);
                });
            };
            
            // 获取扣分规则
            const subtractRulesRequest = store.get('subtract');
            subtractRulesRequest.onsuccess = function() {
                const subtractRules = subtractRulesRequest.result?.rules || [
                    { value: -1, desc: '' },
                    { value: -2, desc: '' }
                ];
                
                subtractRules.forEach(rule => {
                    addRuleItem('subtract', rule.value, rule.desc);
                });
            };
        }

        // 添加规则项
        function addRuleItem(type, value = type === 'add' ? 1 : -1, desc = '') {
            const container = type === 'add' 
                ? document.getElementById('add-rules-container')
                : document.getElementById('subtract-rules-container');
            
            const item = document.createElement('div');
            item.className = `${type}-rule-item flex items-center space-x-3`;
            
            item.innerHTML = `
                <input type="number" class="score-value w-20 p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" 
                       placeholder="分值" ${type === 'add' ? 'min="1"' : 'max="-1"'} value="${value}">
                <input type="text" class="score-desc flex-grow p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" 
                       placeholder="含义描述" value="${desc}">
                <button class="remove-rule-btn text-gray-400 hover:text-danger p-2">
                    <i class="fa fa-trash"></i>
                </button>
            `;
            
            container.appendChild(item);
        }

        // 保存积分规则
        function saveScoreRules() {
            // 收集加分规则
            const addRules = [];
            document.querySelectorAll('.add-rule-item').forEach(item => {
                const value = parseInt(item.querySelector('.score-value').value);
                const desc = item.querySelector('.score-desc').value.trim();
                
                if (isNaN(value) || value <= 0) {
                    showToast('加分值必须是正数', 'error');
                    return false;
                }
                
                addRules.push({ value, desc });
            });
            
            if (addRules.length === 0) {
                showToast('请至少添加一条加分规则', 'error');
                return;
            }
            
            // 收集扣分规则
            const subtractRules = [];
            document.querySelectorAll('.subtract-rule-item').forEach(item => {
                const value = parseInt(item.querySelector('.score-value').value);
                const desc = item.querySelector('.score-desc').value.trim();
                
                if (isNaN(value) || value >= 0) {
                    showToast('扣分值必须是负数', 'error');
                    return false;
                }
                
                subtractRules.push({ value, desc });
            });
            
            if (subtractRules.length === 0) {
                showToast('请至少添加一条扣分规则', 'error');
                return;
            }
            
            // 保存规则
            const transaction = db.transaction('scoreRules', 'readwrite');
            const store = transaction.objectStore('scoreRules');
            
            store.put({ type: 'add', rules: addRules });
            store.put({ type: 'subtract', rules: subtractRules });
            
            transaction.oncomplete = function() {
                showToast('积分规则保存成功', 'success');
                document.getElementById('score-rules-modal').classList.add('hidden');
                updateDashboard(); // 更新仪表盘以应用新规则
                
                // 记录日志
                addLog('更新积分规则');
            };
            
            transaction.onerror = function() {
                showToast('保存积分规则失败: ' + transaction.error, 'error');
            };
        }

        // 加载批量操作分值
        function loadBatchScores(type) {
            const container = document.getElementById('batch-scores-container');
            container.innerHTML = '';
            
            const transaction = db.transaction('scoreRules', 'readonly');
            const store = transaction.objectStore('scoreRules');
            
            const request = store.get(type);
            request.onsuccess = function() {
                const rules = request.result?.rules || [];
                
                if (rules.length === 0) {
                    container.innerHTML = '<p class="col-span-3 text-center text-gray-500">暂无规则，请先设置积分规则</p>';
                    return;
                }
                
                rules.forEach(rule => {
                    const btn = document.createElement('button');
                    btn.className = `p-3 rounded-lg text-center transition-colors ${
                        type === 'add' ? 'bg-success/10 hover:bg-success/20 text-success' : 'bg-danger/10 hover:bg-danger/20 text-danger'
                    }`;
                    btn.dataset.value = rule.value;
                    btn.innerHTML = `
                        <div class="font-bold">${rule.value}</div>
                        <div class="text-xs mt-1 truncate">${rule.desc || '无描述'}</div>
                    `;
                    
                    btn.addEventListener('click', function() {
                        // 移除其他按钮的选中状态
                        document.querySelectorAll('#batch-scores-container button').forEach(b => {
                            b.classList.remove('ring-2', 'ring-primary');
                        });
                        
                        // 添加当前按钮的选中状态
                        this.classList.add('ring-2', 'ring-primary');
                        
                        // 存储选中的分值
                        document.getElementById('confirm-batch').dataset.value = this.dataset.value;
                    });
                    
                    container.appendChild(btn);
                });
            };
        }
        
        // 确认批量操作
        function confirmBatchOperation() {
            const value = document.getElementById('confirm-batch').dataset.value;
            if (!value) {
                showToast('请选择分值', 'warning');
                return;
            }
            
            const reason = document.getElementById('batch-reason').value.trim();
            const valueInt = parseInt(value);
            
            if (selectedStudents.size === 0) {
                showToast('请选择学生', 'warning');
                return;
            }
            
            // 执行批量更新
            const studentIds = Array.from(selectedStudents);
            const transaction = db.transaction('students', 'readwrite');
            const store = transaction.objectStore('students');
            
            let updatedStudents = []; // 存储更新后的学生信息（ID和姓名）
            
            studentIds.forEach(id => {
                const request = store.get(id);
                request.onsuccess = function() {
                    const student = request.result;
                    if (student) {
                        const oldScore = student.score;
                        student.score = oldScore + valueInt;
                        store.put(student);
                        // 保存更新后的学生信息用于日志记录
                        updatedStudents.push({
                            id: student.id,
                            name: student.name,
                            oldScore: oldScore,
                            newScore: student.score
                        });
                    }
                };
            });
            
            transaction.oncomplete = function() {
                const action = valueInt > 0 ? '加分' : '扣分';
                const absValue = Math.abs(valueInt);
                showToast(`已为 ${updatedStudents.length} 名学生批量${action} ${absValue}分`, 'success');
                
                // 新增：记录批量操作历史
                updatedStudents.forEach(student => {
                    addOperationHistory({
                        studentId: student.id,
                        studentName: student.name,
                        oldScore: student.oldScore,
                        newScore: student.newScore,
                        value: valueInt,
                        reason: reason,
                        timestamp: new Date().toISOString(),
                        isBatch: true
                    });
                });
                
                // 关闭模态框
                document.getElementById('batch-operation-modal').classList.add('hidden');
                document.getElementById('confirm-batch').removeAttribute('data-value');
                document.getElementById('batch-reason').value = '';
                
                // 清空选择
                selectedStudents.clear();
                document.getElementById('select-all').checked = false;
                updateBatchOperations();
                
                // 更新界面
                updateDashboard();
                updateRanking();
                
                // 记录日志 - 为每个学生单独记录一条
                const logReason = reason ? `，原因: ${reason}` : '';
                const timestamp = new Date().toLocaleString();
                
                updatedStudents.forEach(student => {
                    addLog(` ${student.name} 批量${action} ${absValue}分${logReason}`);
                });
            };
            
            transaction.onerror = function() {
                showToast('批量操作失败: ' + transaction.error, 'error');
            };
        }

        // 更新排行榜
        function updateRanking() {
            const transaction = db.transaction('students', 'readonly');
            const store = transaction.objectStore('students');
            const request = store.getAll();
            
            request.onsuccess = function() {
                let students = request.result;
                
                // 按积分降序排序
                students.sort((a, b) => b.score - a.score);
                
                const rankingList = document.getElementById('ranking-list');
                
                if (students.length === 0) {
                    rankingList.innerHTML = `
                        <tr>
                            <td colspan="3" class="px-6 py-12 text-center text-gray-500">
                                <div class="flex flex-col items-center">
                                    <i class="fa fa-info-circle text-3xl mb-3 text-gray-400"></i>
                                    <p>暂无积分数据，请先添加学生并进行积分操作</p>
                                </div>
                            </td>
                        </tr>
                    `;
                    
                    // 清空领奖台
                    document.getElementById('rank-1-name').textContent = '--';
                    document.getElementById('rank-1-score').textContent = '0';
                    document.getElementById('rank-2-name').textContent = '--';
                    document.getElementById('rank-2-score').textContent = '0';
                    document.getElementById('rank-3-name').textContent = '--';
                    document.getElementById('rank-3-score').textContent = '0';
                    
                    return;
                }
                
                // 更新领奖台
                if (students.length >= 1) {
                    document.getElementById('rank-1-name').textContent = students[0].name;
                    document.getElementById('rank-1-score').textContent = students[0].score;
                }
                if (students.length >= 2) {
                    document.getElementById('rank-2-name').textContent = students[1].name;
                    document.getElementById('rank-2-score').textContent = students[1].score;
                } else {
                    document.getElementById('rank-2-name').textContent = '--';
                    document.getElementById('rank-2-score').textContent = '0';
                }
                if (students.length >= 3) {
                    document.getElementById('rank-3-name').textContent = students[2].name;
                    document.getElementById('rank-3-score').textContent = students[2].score;
                } else {
                    document.getElementById('rank-3-name').textContent = '--';
                    document.getElementById('rank-3-score').textContent = '0';
                }
                
                // 更新排行榜列表
                rankingList.innerHTML = '';
                students.forEach((student, index) => {
                    const tr = document.createElement('tr');
                    tr.className = 'hover:bg-gray-50 transition-colors';
                    
                    // 前三名添加特殊样式
                    let rankStyle = '';
                    if (index === 0) rankStyle = 'bg-yellow-50';
                    else if (index === 1) rankStyle = 'bg-gray-50';
                    else if (index === 2) rankStyle = 'bg-amber-50';
                    
                    tr.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap ${rankStyle}">
                            <div class="flex items-center">
                                <span class="flex items-center justify-center w-6 h-6 rounded-full ${
                                    index === 0 ? 'bg-yellow-500 text-white' : 
                                    index === 1 ? 'bg-gray-400 text-white' : 
                                    index === 2 ? 'bg-amber-700 text-white' : 
                                    'bg-gray-200 text-gray-700'
                                } text-sm font-medium">
                                    ${index + 1}
                                </span>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap ${rankStyle}">
                            <div class="font-medium text-gray-900">${student.name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap ${rankStyle} ${student.score > 0 ? 'text-success' : student.score < 0 ? 'text-danger' : ''}">
                            <div class="text-sm">${student.score}</div>
                        </td>
                    `;
                    
                    rankingList.appendChild(tr);
                });
            };
            
            request.onerror = function() {
                showToast('加载排行榜失败: ' + request.error, 'error');
            };
        }

        // 导出积分数据
        function exportScores() {
            const transaction = db.transaction('students', 'readonly');
            const store = transaction.objectStore('students');
            const request = store.getAll();
            
            request.onsuccess = function() {
                const students = request.result;
                
                if (students.length === 0) {
                    showToast('没有学生数据可导出', 'warning');
                    return;
                }
                
                // 按姓名排序
                students.sort((a, b) => a.name.localeCompare(b.name));
                
                // 构建TXT内容
                let content = '班级积分数据\n';
                content += '============================\n';
                students.forEach(student => {
                    content += `${student.name}: ${student.score}分\n`;
                });
                content += '============================\n';
                content += `导出时间: ${new Date().toLocaleString()}\n`;
                
                // 创建并下载文件
                const blob = new Blob([content], { type: 'text/plain' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                
                // 生成文件名
                const date = new Date();
                const fileName = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}_班级积分数据.txt`;
                
                a.href = url;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                showToast('积分数据导出成功', 'success');
                
                // 记录日志
                addLog('导出积分数据');
            };
            
            request.onerror = function() {
                showToast('导出积分数据失败: ' + request.error, 'error');
            };
        }

        // 备份数据
        function backupData() {
            const transaction = db.transaction(['students', 'scoreRules', 'logs'], 'readonly');
            const studentsStore = transaction.objectStore('students');
            const rulesStore = transaction.objectStore('scoreRules');
            const logsStore = transaction.objectStore('logs');
            
            let students, rules, logs;
            
            // 获取学生数据
            const studentsRequest = studentsStore.getAll();
            studentsRequest.onsuccess = function() {
                students = studentsRequest.result;
            };
            
            // 获取积分规则
            const rulesRequest = rulesStore.getAll();
            rulesRequest.onsuccess = function() {
                rules = rulesRequest.result;
            };
            
            // 获取日志
            const logsRequest = logsStore.getAll();
            logsRequest.onsuccess = function() {
                logs = logsRequest.result;
            };
            
            transaction.oncomplete = function() {
                // 构建备份数据
                const backupData = {
                    timestamp: new Date().toISOString(),
                    students: students || [],
                    rules: rules || [],
                    logs: logs || []
                };
                
                // 创建并下载文件
                const blob = new Blob([JSON.stringify(backupData, null, 2)], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                
                // 生成文件名
                const date = new Date();
                const fileName = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}_班级积分数据备份.json`;
                
                a.href = url;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                showToast('数据备份成功', 'success');
                
                // 记录日志
                addLog('创建数据备份');
            };
            
            transaction.onerror = function() {
                showToast('数据备份失败: ' + transaction.error, 'error');
            };
        }

        // 导入数据
        function importData(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            // 验证文件类型
            if (file.type !== 'application/json' && !file.name.endsWith('.json')) {
                showToast('请导入JSON格式的备份文件', 'error');
                event.target.value = ''; // 重置文件输入
                return;
            }
            
            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const backupData = JSON.parse(e.target.result);
                    
                    // 验证备份数据格式
                    if (!backupData.students || !backupData.rules) {
                        throw new Error('备份文件格式不正确');
                    }
                    
                    // 确认覆盖现有数据
                    if (!confirm('确定要导入数据吗？这将覆盖现有所有数据！')) {
                        event.target.value = '';
                        return;
                    }
                    
                    // 开始导入
                    const transaction = db.transaction(['students', 'scoreRules', 'logs'], 'readwrite');
                    const studentsStore = transaction.objectStore('students');
                    const rulesStore = transaction.objectStore('scoreRules');
                    const logsStore = transaction.objectStore('logs');
                    
                    // 清空现有数据
                    studentsStore.clear();
                    rulesStore.clear();
                    logsStore.clear();
                    
                    // 导入学生数据
                    backupData.students.forEach(student => {
                        studentsStore.add(student);
                    });
                    
                    // 导入积分规则
                    backupData.rules.forEach(rule => {
                        rulesStore.add(rule);
                    });
                    
                    // 导入日志（如果有）
                    if (backupData.logs && Array.isArray(backupData.logs)) {
                        backupData.logs.forEach(log => {
                            logsStore.add(log);
                        });
                    }
                    
                    transaction.oncomplete = function() {
                        showToast('数据导入成功', 'success');
                        
                        // 更新界面
                        loadStudents();
                        updateDashboard();
                        updateRanking();
                        
                        // 记录日志
                        addLog(`导入数据备份，包含 ${backupData.students.length} 名学生`);
                        
                        // 重置文件输入
                        event.target.value = '';
                    };
                    
                    transaction.onerror = function() {
                        showToast('数据导入失败: ' + transaction.error, 'error');
                        event.target.value = '';
                    };
                    
                } catch (error) {
                    showToast('解析备份文件失败: ' + error.message, 'error');
                    event.target.value = '';
                }
            };
            
            reader.readAsText(file);
        }

        // 加载操作日志
        function loadLogs() {
            const transaction = db.transaction('logs', 'readonly');
            const store = transaction.objectStore('logs');
            const request = store.getAll();
            
            request.onsuccess = function() {
                let logs = request.result;
                
                // 按时间降序排序
                logs.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
                
                const logsContainer = document.getElementById('logs-container');
                
                if (logs.length === 0) {
                    logsContainer.innerHTML = `
                        <div class="text-center text-gray-500 py-10">
                            <i class="fa fa-info-circle text-3xl mb-3 text-gray-400"></i>
                            <p>暂无操作日志</p>
                        </div>
                    `;
                    return;
                }
                
                logsContainer.innerHTML = '';
                logs.forEach(log => {
                    const logItem = document.createElement('div');
                    logItem.className = 'p-3 border-b border-gray-100 hover:bg-gray-50 transition-colors';
                    
                    logItem.innerHTML = `
                        <div class="flex justify-between items-start">
                            <div class="font-medium text-gray-900">${log.content}</div>
                            <div class="text-xs text-gray-500">${new Date(log.timestamp).toLocaleString()}</div>
                        </div>
                    `;
                    
                    logsContainer.appendChild(logItem);
                });
            };
            
            request.onerror = function() {
                showToast('加载日志失败: ' + request.error, 'error');
            };
        }

        // 导出日志
        function exportLogs() {
            const transaction = db.transaction('logs', 'readonly');
            const store = transaction.objectStore('logs');
            const request = store.getAll();
            
            request.onsuccess = function() {
                let logs = request.result;
                
                // 按时间降序排序
                logs.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
                
                if (logs.length === 0) {
                    showToast('没有日志可导出', 'warning');
                    return;
                }
                
                // 构建TXT内容
                let content = '班级积分管理操作日志\n';
                content += '============================\n';
                logs.forEach(log => {
                    content += `[${new Date(log.timestamp).toLocaleString()}] ${log.content}\n`;
                });
                content += '============================\n';
                content += `导出时间: ${new Date().toLocaleString()}\n`;
                
                // 创建并下载文件
                const blob = new Blob([content], { type: 'text/plain' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                
                // 生成文件名
                const date = new Date();
                const fileName = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}_积分管理操作日志.txt`;
                
                a.href = url;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                showToast('日志导出成功', 'success');
            };
            
            request.onerror = function() {
                showToast('导出日志失败: ' + request.error, 'error');
            };
        }

        // 积分清零
        function resetAllScores() {
            const transaction = db.transaction('students', 'readwrite');
            const store = transaction.objectStore('students');
            const request = store.getAll();
            
            request.onsuccess = function() {
                const students = request.result;
                students.forEach(student => {
                    student.score = 0;
                    store.put(student);
                });
            };
            
            transaction.oncomplete = function() {
                showToast('所有学生积分已清零', 'success');
                
                // 更新界面
                updateDashboard();
                updateRanking();
                loadStudents();
                
                // 记录日志
                addLog('所有学生积分清零');
            };
            
            transaction.onerror = function() {
                showToast('积分清零失败: ' + transaction.error, 'error');
            };
        }

        // 系统初始化
        function resetSystem() {
            if (confirm('确定要初始化系统吗？这将清除所有数据，包括学生信息、积分和日志，且不可恢复！')) {
                // 关闭当前数据库连接
                if (db) {
                    db.close();
                }
                
                // 删除整个数据库
                const deleteRequest = indexedDB.deleteDatabase('ClassScoreDB');
                
                deleteRequest.onsuccess = function() {
                    showToast('系统已初始化，页面即将刷新', 'success');
                    
                    // 刷新页面以重新初始化数据库
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                };
                
                deleteRequest.onerror = function() {
                    showToast('系统初始化失败: ' + deleteRequest.error, 'error');
                };
                
                deleteRequest.onblocked = function() {
                    showToast('数据库操作被阻止，请关闭其他打开的页面', 'error');
                };
            }
        }

        // 添加操作日志
        function addLog(content) {
            const transaction = db.transaction('logs', 'readwrite');
            const store = transaction.objectStore('logs');
            
            store.add({
                content: content,
                timestamp: new Date().toISOString()
            });
        }

        // 显示提示信息
        function showToast(message, type = 'success') {
            const toast = document.getElementById('toast');
            const toastIcon = document.getElementById('toast-icon');
            const toastMessage = document.getElementById('toast-message');
            
            // 设置图标和样式
            switch (type) {
                case 'success':
                    toastIcon.className = 'fa fa-check-circle mr-2 text-success';
                    break;
                case 'error':
                    toastIcon.className = 'fa fa-times-circle mr-2 text-danger';
                    break;
                case 'warning':
                    toastIcon.className = 'fa fa-exclamation-triangle mr-2 text-warning';
                    break;
                case 'info':
                    toastIcon.className = 'fa fa-info-circle mr-2 text-info';
                    break;
            }
            
            // 设置消息
            toastMessage.textContent = message;
            
            // 显示提示
            toast.classList.remove('translate-y-20', 'opacity-0');
            toast.classList.add('translate-y-0', 'opacity-100');
            
            // 3秒后隐藏
            setTimeout(() => {
                toast.classList.remove('translate-y-0', 'opacity-100');
                toast.classList.add('translate-y-20', 'opacity-0');
            }, 3000);
        }

        // 新增：添加操作历史记录
        function addOperationHistory(operation) {
            const transaction = db.transaction('operationHistory', 'readwrite');
            const store = transaction.objectStore('operationHistory');
            
            store.add(operation);
            
            transaction.oncomplete = function() {
                // 重新加载操作历史
                loadOperationHistory();
            };
        }

        // 新增：加载操作历史记录
        function loadOperationHistory() {
            const transaction = db.transaction('operationHistory', 'readonly');
            const store = transaction.objectStore('operationHistory');
            const request = store.getAll();
            
            request.onsuccess = function() {
                operationHistory = request.result || [];
                
                // 按时间降序排序
                operationHistory.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
                
                // 更新撤销按钮状态
                const undoBtn = document.getElementById('undo-btn');
                if (operationHistory.length > 0) {
                    undoBtn.disabled = false;
                    undoBtn.classList.remove('opacity-50', 'cursor-not-allowed');
                } else {
                    undoBtn.disabled = true;
                    undoBtn.classList.add('opacity-50', 'cursor-not-allowed');
                }
            };
        }

        // 新增：撤销上一步操作
        function undoLastOperation() {
            if (operationHistory.length === 0) {
                showToast('没有可撤销的操作', 'warning');
                return;
            }
            
            const lastOperation = operationHistory[0];
            
            const transaction = db.transaction(['students', 'operationHistory'], 'readwrite');
            const studentsStore = transaction.objectStore('students');
            const historyStore = transaction.objectStore('operationHistory');
            
            // 恢复学生积分
            const request = studentsStore.get(lastOperation.studentId);
            request.onsuccess = function() {
                const student = request.result;
                if (student) {
                    student.score = lastOperation.oldScore;
                    studentsStore.put(student);
                }
            };
            
            // 从历史记录中删除该操作
            historyStore.delete(lastOperation.id);
            
            transaction.oncomplete = function() {
                const action = lastOperation.value > 0 ? '加分' : '扣分';
                const absValue = Math.abs(lastOperation.value);
                showToast(`已撤销对 ${lastOperation.studentName} 的${action} ${absValue}分操作`, 'success');
                
                // 重新加载操作历史
                loadOperationHistory();
                
                // 更新界面
                updateDashboard();
                updateRanking();
                
                // 记录日志
                addLog(`撤销操作: ${lastOperation.studentName} 的${action} ${absValue}分操作`);
            };
            
            transaction.onerror = function() {
                showToast('撤销操作失败: ' + transaction.error, 'error');
            };
        }

        // 新增：根据姓名过滤学生
        function filterStudentsByName(searchTerm) {
            const studentCards = document.querySelectorAll('#student-cards-container > div');
            
            studentCards.forEach(card => {
                const studentName = card.dataset.studentName;
                
                if (searchTerm.trim() === '') {
                    // 搜索为空，显示所有卡片
                    card.style.display = 'block';
                    card.classList.remove('highlight');
                } else if (studentName && studentName.toLowerCase().includes(searchTerm.toLowerCase())) {
                    // 匹配搜索条件，显示并高亮卡片
                    card.style.display = 'block';
                    card.classList.add('highlight');
                } else {
                    // 不匹配，隐藏卡片
                    card.style.display = 'none';
                    card.classList.remove('highlight');
                }
            });
        }
    </script>
</body>
</html>